var express = require('express');
var router = express.Router();
var db = require('../data');
var request = require('request');
var encryption = require('encryption');
var access_token = require('./develop/access_token');
var crypto = require('crypto');
/* GET home page. */

var randomString = function(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function sha1(str) {
    var md5sum = crypto.createHash('sha1');
    md5sum.update(str);
    str = md5sum.digest('hex');
    return str;
}

var GET = function(req, res, next){

    var model = db.model;

    var phone = req.query.phone;


    var noncestr = randomString(32);
    var jsapi_ticket = access_token.jsTicket;
    var timestamp = new Date().getTime();
    var url = 'http://'+req.headers.host+req.originalUrl;

    var _key = [
        "noncestr="+noncestr,
        "jsapi_ticket="+jsapi_ticket,
        "timestamp="+timestamp,
        "url="+url
    ];

    var signature = _key.sort();

    signature = sha1(signature.join('&'));


    var _data = {
        appid: access_token.appId,
        timestamp: timestamp,
        noncestr: noncestr,
        signature: signature,
        jsApiList: "'onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone','startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice','stopVoice','onVoicePlayEnd','uploadVoice','downloadVoice','chooseImage','previewImage','uploadImage','downloadImage','translateVoice','getNetworkType','openLocation','getLocation','hideOptionMenu','showOptionMenu','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem','showAllNonBaseMenuItem','closeWindow','scanQRCode','chooseWXPay','openProductSpecificView','addCard','chooseCard','openCard'"
    };


    model.odds.findOne(function(err, data){
        if(err)
            var returnData = {
                weixin: _data
            };
        else{
            var returnData = {
                odds : [data.a, data.b, data.c, data.d, 100 - (data.a+data.b+data.c+data.d)],
                weixin: _data
            };
        };
        res.render('prize', returnData);

    });




};

router.get('/', GET);

module.exports = router;
